import os
from urllib.parse import urlparse
from urllib.request import urlopen

def save_html_page(url, output_dir='./'):
    try:
        # 使用urlopen获取网页内容
        with urlopen(url) as response:
            html_content = response.read().decode('utf-8')

        # 解析URL获取路径
        parsed_url = urlparse(url)
        path = parsed_url.path

        # 提取文件名
        file_name = os.path.basename(path)
        if not file_name or file_name == '':
            file_name = 'index.html'
        elif not file_name.endswith('.html'):
            file_name += '.html'

        # 构建完整文件路径
        file_path = os.path.join(output_dir, file_name)

        # 写入文件
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(html_content)

        print(f'成功保存页面到: {file_path}')
        return file_path

    except Exception as e:
        print(f'保存失败: {e}')

save_html_page('https://www.runoob.com/mysql/mysql-tutorial.html')